package cn.my.android_demo;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;

import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.security.SignatureException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import cn.my.android_demo.api.Api;
import cn.my.android_demo.databinding.ActivityMainBinding;
import cn.my.android_demo.model.AuthToken;
import cn.my.android_demo.model.MainViewModel;
import cn.my.android_demo.model.ObjectBox;
import io.objectbox.Box;
import io.objectbox.BoxStore;
import okhttp3.OkHttpClient;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class MainActivity extends AppCompatActivity {
    private static String TAG = MainActivity.class.getName();
    private Retrofit retrofit;
    private Api api;
    private final static String BaseURL =
//            "http://192.168.1.9:9086";
            "https://102.12.1.2";
    BoxStore boxStore;
    Box<AuthToken> authTokenBox = null;

    ActivityMainBinding binding;
    MainViewModel mainViewModel;

    @SuppressLint("CustomX509TrustManager")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
//        setContentView(R.layout.activity_main);

        binding = DataBindingUtil.setContentView(this,R.layout.activity_main);
        //旧版本
        //mainViewModel = ViewModelProviders.of(this).get(MainViewModel.class);
        // extends AndroidViewModel
        mainViewModel=new ViewModelProvider(this,new ViewModelProvider.AndroidViewModelFactory(getApplication())).get(MainViewModel.class);
        // extends ViewModel
       // mainViewModel=new ViewModelProvider(this,new ViewModelProvider.NewInstanceFactory()).get(MainViewModel.class);

        // 完成绑定
        binding.setVm(mainViewModel);
        // 建立感应
        binding.setLifecycleOwner(this);

        ObjectBox.init(this);
        boxStore = ObjectBox.get();
        authTokenBox = boxStore.boxFor(AuthToken.class);

        SSLContext sslContext = null;
        TrustManager[] trustManagers = new TrustManager[0];
        try {
            // 从res/raw目录下读取证书文件
            InputStream certificateInputStream = getResources().openRawResource(R.raw.example);
            CertificateFactory certificateFactory = null;
            certificateFactory = CertificateFactory.getInstance("X.509");

            X509Certificate certificate = (X509Certificate) certificateFactory.generateCertificate(certificateInputStream);
            // 创建TrustManager，信任指定的服务器证书
            trustManagers = new TrustManager[]{
                    new X509TrustManager() {
                        @SuppressLint("TrustAllX509TrustManager")
                        @Override
                        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                            // Do nothing
                        }

                        @Override
                        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                            for (X509Certificate cert : chain) {
                                cert.checkValidity();
                                try {
                                    cert.verify(certificate.getPublicKey());
                                } catch (InvalidKeyException | NoSuchAlgorithmException |
                                         NoSuchProviderException | SignatureException e) {
                                    e.printStackTrace();
                                }
                            }
                        }

                        @Override
                        public X509Certificate[] getAcceptedIssuers() {
                            return new X509Certificate[0];
                        }
                    }
            };
            // 创建SSLContext并设置TrustManager
            sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, trustManagers, new SecureRandom());
        } catch (CertificateException | KeyManagementException | NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        // 创建OkHttpClient并设置SSLContext
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .sslSocketFactory(sslContext.getSocketFactory(), (X509TrustManager) trustManagers[0])
                .hostnameVerifier((hostname, session) -> true)
                .build();

        retrofit = new Retrofit.Builder().
                baseUrl(BaseURL).
                client(okHttpClient).
                addConverterFactory(GsonConverterFactory.create()).
                build();
        api = retrofit.create(Api.class);
    }

    public void onLogin(View view) {

        Call<ResponseBody> respCall = api.validImgCode(50, 150, "dyj", "login", 0);
        respCall.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    assert response.body() != null;
                    Log.i(TAG, "onResponse: " + response.body().string());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(@NonNull Call<ResponseBody> call, @NonNull Throwable throwable) {
                Log.e(TAG, "onFailure: " + throwable.getMessage());
            }
        });
/*
       Call<ResponseBody> respCall = api.login(new LoginForm("yingjie","123456"));
       respCall.enqueue(new Callback<ResponseBody>() {
           @Override
           public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
               try {
                   assert response.body() != null;
                   Log.i(TAG, "onResponse: "+response.body().string());
               } catch (IOException e) {
                   e.printStackTrace();
               }
           }

           @Override
           public void onFailure(@NonNull Call<ResponseBody> call, @NonNull Throwable throwable) {
               Log.e(TAG, "onFailure: "+throwable.getMessage());
           }
       });*/
    }
}

